import { marked } from 'marked';

/**
 * 复制工具类
 * 提供多种格式的复制功能
 */
export class CopyUtils {
  constructor(toastFn = console.log) {
    this.toast = toastFn;
  }

  /**
   * 复制为纯文本
   */
  async copyAsText(markdown) {
    try {
      const plainText = this.markdownToPlainText(markdown);
      await navigator.clipboard.writeText(plainText);
      this.toast("已复制为纯文本", "success");
      return true;
    } catch (error) {
      console.error("复制失败:", error);
      this.toast("复制失败", "error");
      return false;
    }
  }

  /**
   * 复制为 HTML 格式
   */
  async copyAsHtml(markdown) {
    try {
      const html = marked(markdown, {
        breaks: true,
        gfm: true,
        headerIds: false,
        mangle: false
      });
      
      const styledHtml = this.createStyledHtml(html);
      const plainText = this.markdownToPlainText(markdown);
      
      const clipboardItem = new ClipboardItem({
        'text/html': new Blob([styledHtml], { type: 'text/html' }),
        'text/plain': new Blob([plainText], { type: 'text/plain' })
      });
      
      await navigator.clipboard.write([clipboardItem]);
      this.toast("已复制为 HTML（保留样式）", "success");
      return true;
    } catch (error) {
      console.error("复制 HTML 失败:", error);
      return await this.copyAsText(markdown);
    }
  }

  /**
   * 复制为 Word 兼容格式
   */
  async copyAsWordHtml(markdown) {
    try {
      const html = marked(markdown, {
        breaks: true,
        gfm: true,
        headerIds: false,
        mangle: false
      });
      
      const wordHtml = this.createWordCompatibleHtml(html);
      const plainText = this.markdownToPlainText(markdown);
      const rtfContent = this.createRtfContent(markdown);
      
      const clipboardItem = new ClipboardItem({
        'text/html': new Blob([wordHtml], { type: 'text/html' }),
        'text/plain': new Blob([plainText], { type: 'text/plain' }),
        'text/rtf': new Blob([rtfContent], { type: 'text/rtf' })
      });
      
      await navigator.clipboard.write([clipboardItem]);
      this.toast("已复制为 Word 兼容格式", "success");
      return true;
    } catch (error) {
      console.error("Word 格式复制失败:", error);
      return await this.copyAsText(markdown);
    }
  }

  /**
   * 复制为 Office 格式（与 Word 格式相同）
   */
  async copyAsOffice(markdown) {
    return await this.copyAsWordHtml(markdown);
  }

  /**
   * 复制 Markdown 源码
   */
  async copyAsMarkdown(markdown) {
    try {
      await navigator.clipboard.writeText(markdown);
      this.toast("已复制 Markdown 源码", "success");
      return true;
    } catch (error) {
      console.error("复制 Markdown 失败:", error);
      this.toast("复制失败", "error");
      return false;
    }
  }

  /**
   * 创建基础的样式化 HTML
   */
  createStyledHtml(content) {
    return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #24292f;
            background-color: #ffffff;
            max-width: none;
            margin: 0;
            padding: 16px;
            word-wrap: break-word;
        }
        
        h1, h2, h3, h4, h5, h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }
        
        h1 {
            font-size: 2em;
            border-bottom: 1px solid #d0d7de;
            padding-bottom: 0.3em;
        }
        
        h2 {
            font-size: 1.5em;
            border-bottom: 1px solid #d0d7de;
            padding-bottom: 0.3em;
        }
        
        p {
            margin-top: 0;
            margin-bottom: 16px;
        }
        
        code {
            background-color: #f6f8fa;
            border-radius: 6px;
            font-size: 85%;
            margin: 0;
            padding: 0.2em 0.4em;
            font-family: ui-monospace, SFMono-Regular, 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;
        }
        
        pre {
            background-color: #f6f8fa;
            border-radius: 6px;
            font-size: 85%;
            line-height: 1.45;
            overflow: auto;
            padding: 16px;
            margin-bottom: 16px;
        }
        
        blockquote {
            padding: 0 1em;
            color: #656d76;
            border-left: 0.25em solid #d0d7de;
            margin: 0 0 16px 0;
        }
        
        table {
            border-spacing: 0;
            border-collapse: collapse;
            margin-bottom: 16px;
            width: 100%;
        }
        
        table th,
        table td {
            padding: 6px 13px;
            border: 1px solid #d0d7de;
        }
        
        table th {
            font-weight: 600;
            background-color: #f6f8fa;
        }
    </style>
</head>
<body>
    ${content}
</body>
</html>`;
  }

  /**
   * 创建 Word 兼容的 HTML
   */
  createWordCompatibleHtml(content) {
    return `
<html xmlns:o="urn:schemas-microsoft-com:office:office"
      xmlns:w="urn:schemas-microsoft-com:office:word"
      xmlns="http://www.w3.org/TR/REC-html40">
<head>
    <meta charset="utf-8">
    <meta name=ProgId content=Word.Document>
    <meta name=Generator content="Microsoft Word 15">
    <style>
        body {
            font-family: "Calibri", "Microsoft YaHei", sans-serif;
            font-size: 11.0pt;
            line-height: 1.15;
            color: #000000;
            background: white;
        }
        
        h1 {
            font-size: 18.0pt;
            font-weight: bold;
            color: #2E75B5;
            margin-top: 12.0pt;
            margin-bottom: 6.0pt;
        }
        
        h2 {
            font-size: 16.0pt;
            font-weight: bold;
            color: #2E75B5;
            margin-top: 10.0pt;
            margin-bottom: 6.0pt;
        }
        
        h3 {
            font-size: 14.0pt;
            font-weight: bold;
            color: #1F4E79;
            margin-top: 10.0pt;
            margin-bottom: 6.0pt;
        }
        
        p {
            margin-top: 0pt;
            margin-bottom: 8.0pt;
            line-height: 1.08;
        }
        
        ul, ol {
            margin-top: 0pt;
            margin-bottom: 8.0pt;
            margin-left: 36pt;
        }
        
        blockquote {
            margin-left: 36pt;
            margin-right: 36pt;
            border-left: 3pt solid #CCCCCC;
            padding-left: 12pt;
            font-style: italic;
            color: #666666;
        }
        
        code {
            font-family: "Consolas", "Courier New", monospace;
            font-size: 10.0pt;
            background-color: #F2F2F2;
            border: 1pt solid #CCCCCC;
            padding: 1pt 4pt;
        }
        
        pre {
            font-family: "Consolas", "Courier New", monospace;
            font-size: 10.0pt;
            background-color: #F8F8F8;
            border: 1pt solid #CCCCCC;
            padding: 8pt;
            margin-bottom: 8.0pt;
        }
        
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 8.0pt;
        }
        
        th, td {
            border: 1pt solid #CCCCCC;
            padding: 4pt 8pt;
            text-align: left;
        }
        
        th {
            background-color: #F2F2F2;
            font-weight: bold;
        }
    </style>
</head>
<body>
    ${content}
</body>
</html>`;
  }

  /**
   * 创建 RTF 格式内容
   */
  createRtfContent(markdown) {
    let rtf = '{\\rtf1\\ansi\\deff0 {\\fonttbl {\\f0 Times New Roman;}}';
    const lines = markdown.split('\n');
    
    lines.forEach(line => {
      if (line.startsWith('# ')) {
        rtf += `{\\f0\\fs24\\b ${this.escapeRtf(line.substring(2))}\\par}`;
      } else if (line.startsWith('## ')) {
        rtf += `{\\f0\\fs20\\b ${this.escapeRtf(line.substring(3))}\\par}`;
      } else if (line.startsWith('### ')) {
        rtf += `{\\f0\\fs16\\b ${this.escapeRtf(line.substring(4))}\\par}`;
      } else if (line.startsWith('- ') || line.startsWith('* ')) {
        rtf += `{\\f0\\fs12 \\bullet ${this.escapeRtf(line.substring(2))}\\par}`;
      } else if (line.trim() === '') {
        rtf += '\\par';
      } else {
        let text = line;
        text = text.replace(/\*\*(.*?)\*\*/g, '{\\b $1}');
        text = text.replace(/\*(.*?)\*/g, '{\\i $1}');
        rtf += `{\\f0\\fs12 ${this.escapeRtf(text)}\\par}`;
      }
    });
    
    rtf += '}';
    return rtf;
  }

  /**
   * RTF 转义函数
   */
  escapeRtf(text) {
    return text
      .replace(/\\/g, '\\\\')
      .replace(/\{/g, '\\{')
      .replace(/\}/g, '\\}');
  }

  /**
   * 将 Markdown 转换为纯文本
   */
  markdownToPlainText(markdown) {
    return markdown
      // 移除代码块
      .replace(/```[\s\S]*?```/g, (match) => {
        const lines = match.split('\n');
        return lines.slice(1, -1).join('\n');
      })
      // 移除行内代码
      .replace(/`([^`]+)`/g, '$1')
      // 移除链接，保留文本
      .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
      // 移除图片
      .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
      // 移除标题标记
      .replace(/^#{1,6}\s+/gm, '')
      // 移除粗体和斜体
      .replace(/\*\*([^*]+)\*\*/g, '$1')
      .replace(/\*([^*]+)\*/g, '$1')
      .replace(/__([^_]+)__/g, '$1')
      .replace(/_([^_]+)_/g, '$1')
      // 移除删除线
      .replace(/~~([^~]+)~~/g, '$1')
      // 移除引用标记
      .replace(/^>\s*/gm, '')
      // 移除列表标记
      .replace(/^[\s]*[-*+]\s+/gm, '• ')
      .replace(/^[\s]*\d+\.\s+/gm, '')
      // 移除任务列表标记
      .replace(/^[\s]*- \[[x ]\]\s+/gm, '• ')
      // 移除水平线
      .replace(/^---+$/gm, '')
      // 清理多余空行
      .replace(/\n\s*\n\s*\n/g, '\n\n')
      .trim();
  }
}

/**
 * 创建默认的复制工具实例
 */
export function createCopyUtils(toastFn) {
  return new CopyUtils(toastFn);
}

/**
 * 导出便捷函数
 */
export const copyUtils = {
  copyAsText: (markdown, toastFn) => new CopyUtils(toastFn).copyAsText(markdown),
  copyAsHtml: (markdown, toastFn) => new CopyUtils(toastFn).copyAsHtml(markdown),
  copyAsWordHtml: (markdown, toastFn) => new CopyUtils(toastFn).copyAsWordHtml(markdown),
  copyAsOffice: (markdown, toastFn) => new CopyUtils(toastFn).copyAsOffice(markdown),
  copyAsMarkdown: (markdown, toastFn) => new CopyUtils(toastFn).copyAsMarkdown(markdown),
};
